package fr.sedoo.commons.server.image;

import java.io.ByteArrayInputStream;
import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.apache.commons.io.FileUtils;

import fr.sedoo.commons.client.DefaultApplication;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.server.storedfile.TmpFileManager;
import fr.sedoo.commons.server.storedfile.dao.StoredFileDAO;
import fr.sedoo.commons.shared.domain.StoredFile;

@Path("/image")
public class ImageService {

	StoredFileDAO storedFileDAO;

	@GET
	@Path("/isAlive")
	public Response getVersion() {
		String answer = "Yes";
		return Response.status(200).entity(answer).build();
	}

	@GET
	@Path("/tmp/{fileName}")
	@Produces("image/*")
	public Response getTmpImage(@PathParam("fileName") String fileName) {
		try {
			String pathForFile = TmpFileManager.getPathForFile(StringUtil.trimToEmpty(fileName));
			if (StringUtil.isEmpty(pathForFile)) {
				return Response.status(404).build();
			} else {
				File tmpFile = new File(pathForFile);
				if (tmpFile.exists() == false) {
					return Response.status(404).build();
				} else {
					return Response.ok(new ByteArrayInputStream(FileUtils.readFileToByteArray(tmpFile))).build();
				}
			}
		} catch (Exception e) {
			return Response.status(404).build();
		}
	}

	@GET
	@Path("/stored/{uuid}")
	@Produces("image/*")
	public Response getStoredImage(@PathParam("uuid") String uuid) {
		try {
			initDao();
			StoredFile aux = storedFileDAO.findByAttacherUuid(uuid);
			if ((aux.getContent() == null) || (aux.getContent().length == 0)) {
				return Response.status(404).build();
			}
			return Response.ok(new ByteArrayInputStream(aux.getContent())).build();
		} catch (Exception e) {
			return Response.status(404).build();
		}
	}

	private void initDao() {
		if (storedFileDAO == null) {
			storedFileDAO = (StoredFileDAO) DefaultApplication.getSpringBeanFactory().getBeanByName(StoredFileDAO.BEAN_NAME);
		}
	}

}
